#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    CaptureDevice::initialize();
    c = new CaptureDevice();
    c->startStream();

    colorView = new ViewPanel(this, COLOR);
    this->ui->view_2->layout()->addWidget(colorView);

    depthView = new ViewPanel(this, DEPTH);
    this->ui->view_1->layout()->addWidget(depthView);

    _3dView = new ViewPanel(this, _3D);
    this->ui->view_3->layout()->addWidget(_3dView);

    activeView = new ViewPanel(this);
    this->ui->activeView->layout()->addWidget(activeView);

    this->setActiveView(COLOR);

    qRegisterMetaType<StreamSource>("StreamSource");

    connect(c->getColorFrameListener(),
            SIGNAL(newFrame(const void*,int,int,StreamSource)),
            this->colorView,
            SLOT(updateImage(const void*,int,int,StreamSource)),
            Qt::BlockingQueuedConnection);

    connect(this->colorView,
            SIGNAL(selected(View)),
            this,
            SLOT(setActiveView(View)));

    connect(c->getDepthFrameListener(),
            SIGNAL(newFrame(const void*,int,int,StreamSource)),
            this->depthView,
            SLOT(updateImage(const void*,int,int,StreamSource)),
            Qt::BlockingQueuedConnection);

    connect(this->depthView,
            SIGNAL(selected(View)),
            this,
            SLOT(setActiveView(View)));

}

void MainWindow::setActiveView(View v){

    //Disconnecting
    switch(currentView){
    case COLOR:{
        disconnect(c->getColorFrameListener(),
                   SIGNAL(newFrame(const void*,int,int,StreamSource)),
                   this->activeView,
                   SLOT(updateImage(const void*,int,int,StreamSource)));
        break;
    }
    case DEPTH:{
        disconnect(c->getDepthFrameListener(),
                                  SIGNAL(newFrame(const void*,int,int,StreamSource)),
                                  this->activeView,
                                  SLOT(updateImage(const void*,int,int,StreamSource)));
    }
    }

    //Connecting
    switch(v){
    case COLOR:{
        connect(c->getColorFrameListener(),
                SIGNAL(newFrame(const void*,int,int,StreamSource)),
                this->activeView,
                SLOT(updateImage(const void*,int,int,StreamSource)),
                Qt::BlockingQueuedConnection);
        break;
    }
    case DEPTH:{
        connect(c->getDepthFrameListener(),
                        SIGNAL(newFrame(const void*,int,int,StreamSource)),
                        this->activeView,
                        SLOT(updateImage(const void*,int,int,StreamSource)),
                        Qt::BlockingQueuedConnection);
        break;
    }
    }

    currentView = v;

}

MainWindow::~MainWindow()
{
    delete ui;

    delete colorView;
}

